package com.unlcn.ils.sales.backend.util;

import java.math.BigDecimal;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

public class RandomUtils {

    /**
     * 生成N位数验证码存到redis并设置有效时间为60秒
     *
     * @param args
     */
    public static void main(String[] args) {
        for (int j = 0; j < 100000; j++) {
            String num = bitInteger(4);
            System.out.println(num);
        }

        Integer ss = 1;
        BigDecimal cost = BigDecimal.valueOf(ss).divide(BigDecimal.valueOf(100));
        System.out.println(cost);
    }

    /**
     * 生成几位数验证码
     *
     * @return
     */
    public static String bitInteger(int len) {
        String max = "1";
        for (int i = 0; i < len; i++) {
            max += 0;
        }
        String num = String.valueOf(ThreadLocalRandom.current().nextInt(Integer.parseInt(max) - 1));
        if (num.length() < len) {
            int count = len - num.length();
            for (int i = 0; i < count; i++) {
                num += "0";
            }
        }
        return num;
    }

    /**
     * 自定义进制(0,1没有加入,容易与o,l混淆)
     */
    private static final char[] r = new char[]{'q', 'w', 'e', '8', 'a', 's', '2', 'd', 'z', 'x', '9', 'c', '7', 'p',
            '5', 'i', 'k', '3', 'm', 'j', 'u', 'f', 'r', '4', 'v', 'y', 'l', 't', 'n', '6', 'b', 'g', 'h'};

    /**
     * (不能与自定义进制有重复)
     */
    private static final char b = 'o';

    /**
     * 进制长度
     */
    private static final int binLen = r.length;

    /**
     * 序列最小长度
     */
    private static final int s = 6;

    /**
     * 生成六位邀请码
     *
     * @param id ID
     * @return 随机码
     */
    public static String toSerialCode(long id) {
        char[] buf = new char[32];
        int charPos = 32;

        while ((id / binLen) > 0) {
            int ind = (int) (id % binLen);
            // System.out.println(num + "-->" + ind);
            buf[--charPos] = r[ind];
            id /= binLen;
        }
        buf[--charPos] = r[(int) (id % binLen)];
        // System.out.println(num + "-->" + num % binLen);
        String str = new String(buf, charPos, (32 - charPos));
        // 不够长度的自动随机补全
        if (str.length() < s) {
            StringBuilder sb = new StringBuilder();
            sb.append(b);
            Random rnd = new Random();
            for (int i = 1; i < s - str.length(); i++) {
                sb.append(r[rnd.nextInt(binLen)]);
            }
            str += sb.toString();
        }
        return str;
    }
}

